"""
    1.请求数据
    2.解析数据
    3.保存数据
"""

import time
# 1.请求数据
import requests
# 2.解析数据
import re
# 3.保存数据
import os

def 请求数据(playlistid:str):
    listapi = f'https://music.163.com/playlist?id={playlistid}'
    cookies = {"os": "pc"} # 可显示全播放列表  添加这个Cookies
    # h_data = requests.get(listapi,headers=ua,cookies=cookies).text
    h_data = requests.get(listapi,headers=ua).text
    解析数据(h_data)
# 2.解析数据
def 解析数据(data:str):
    music_list = re.findall('<li><a href="/song\?id=(.*?)">(.*?)</a></li>',data)
    for music in music_list:
        try:
            保存数据(music[1],music[0])
        except BaseException as e:
            print("报错 --->",e)
            continue # 保存跳过
        time.sleep(3)
# 3.保存数据
def 保存数据(name:str,musicid:str):
    name = name.replace("/","",-1) # 是为了 "/“ 会影响保存路径 -（报错）
    req = requests.get(f"http://music.163.com/song/media/outer/url?id={musicid}")
    if req.status_code == 200:
        path = os.path.abspath(f'./tmp/{input_id}')
        if not os.path.exists(path):
            os.mkdir(path)
        print(f"{musicid}--->{path}")
        with open(f'{path}/{name}.mp3',"wb") as f:
            f.write(req.content)
            f.close()

if __name__ == '__main__':
# 目标 https://music.163.com/?from=itab#/playlist?id=      4934616945
# 'https://music.163.com/playlist?id=[歌单ID]'
# 下载
# http://music.163.com/song/media/outer/url?id=[音乐ID]
    ua = {"user-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.0.0 Safari/537.36"}
    input_id = input("请输入歌单Id:")
    请求数据(str(input_id))

